import {Action, ThunkAction, configureStore} from '@reduxjs/toolkit';
import {rootSlice} from './rootSlice';
import {thunk} from 'redux-thunk';
import {useDispatch, TypedUseSelectorHook, useSelector} from 'react-redux';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { persistStore, persistReducer,FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER } from 'redux-persist';
import { injectApi } from '../http/http';

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
};
const persistedReducer = persistReducer(persistConfig, rootSlice.reducer);

// 1、定义store
export const store = configureStore({
  // 1.1 组合各个reducer
  reducer: {
    root: persistedReducer,
  },
  // 1.2 添加中间件
  middleware: getDefaultMiddleware => getDefaultMiddleware({
    serializableCheck: {
      ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
    },
  }).concat(thunk),
});
export const persistor = persistStore(store, null, () => {
  console.log('store rehydrated');
  if (store.getState().root.user) {
    injectApi('token', (config:any) => {
      config.headers = {
        ...config.headers,
        token: store.getState().root.user.token,
      };
      config.params = {
        ...config.params,
        token: store.getState().root.user.token,
      };
    });
  }
});
export type AppThunk = ThunkAction<void, RootState, null, Action<string>>;
// 定义RootState，为了能够更好的支持TS
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
// 定义带类型的dispatch和selector hook，为了能够在整个App中使用正确的TS类型
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
